<template>
  <div class="f2bpmui-datagrid-vuetable-container">
    <div v-if="toolbar&&toolbar.buttons.length>0" id="grid-toolbar" class="grid-toolbar">
      <el-button-group>
        <el-button :code="btn.code" v-for="(btn,index) in toolbar.buttons" size="small" @click="toolbarClick(btn,$event)" :type="btn.status"><i :class="btn.icon"></i><span v-html="btn.name"></span></el-button>
      </el-button-group>
    </div>
    <el-table ref="f2bpmuiVuetable" border="true" @select="selectionChange" @select-all="selectAll" :key="tableKey" class="f2bpmui-datagrid-vuetable" id="grid" size="small" :height="tableHeight" :stripe="stripe" :border="border" row-key="pk" v-loading="loading" :data="rows" element-loading-text="加载中" fit highlight-current-row @cell-dblclick="celldblclick" @sort-change="sortChange" @header-contextmenu="headRightClick">
       <!--单选-->
      <el-table-column v-if="showCheckbox&&checkBoxType=='radio'" fixed="left" dir="" width="40" align="center" header-align="center">
        <template slot="header" slot-scope="scope">
          <el-checkbox v-model="checkedAll" @change="checkAllChange" v-if="checkBoxType=='checkbox'"></el-checkbox>
        </template>
        <template slot-scope="scope">
          <!-- <el-checkbox :checked="scope.row._checked" @change="checked=>checkedChange(checked, scope.row)" v-if="checkBoxType=='checkbox'"></el-checkbox> -->
          <el-radio style="margin-left: 3px" v-model="radioVal" :label="scope.row" name="radio"  @change="radioChange"  ><span></span></el-radio>
        </template>
      </el-table-column>
      <!--多选-->
      <el-table-column  v-if="showCheckbox&&checkBoxType=='checkbox'" type="selection" fixed="left"  align="center" width="45">
      </el-table-column>

      <el-table-column label="序号" type="index" v-if="showSeq" fixed="left" width="50" align="center" :index="indexMethod">
      </el-table-column>

      <el-table-column :label="col.title" v-if="!col.hidden&&col.type!='seq'&&col.type!='radio'&&col.type!='checkbox'" :prop="col.field" :formatter="col.formatter" header-align="center" :sortable="col.sort ? 'custom' : false" :width="col.width" :fixed="col.fixed" :align="col.align" v-for="(col, index) in columns">
        <template slot-scope="scope">
          <div v-if="col.formatter != undefined" v-html="filterFormatter(scope.row, col, scope.row[col.field], index) "></div>
          <!--render 方式-->
          <div v-else-if="col.slots != undefined">
            {{ renderToHtml(col, scope.row, index) }}
            <slot :name="col.field"></slot>
          </div>
          <div v-else v-html="scope.row[col.field]"></div>
        </template>

      </el-table-column>

    </el-table>
    <el-pagination v-if="ispager" @size-change="pageSizeChange" @current-change="pageChange" :current-page="tablePage.currentPage" :page-sizes="tablePage.pageSizes" :page-size="tablePage.pageSize" :layout="tablePage.layout" :total="tablePage.total">
    </el-pagination>
    <div v-show="menuVisible" id="gridHeadMenu" :class="contextMenu.className+' treeRightMenu'">
      <el-menu size="mini" id="menu" @select="headMenuClickEvent" text-color="#000">
        <el-menu-item size="mini" :index="item.code" v-for="item in contextMenu.header.options">
          <i :class="item.prefixIcon"></i>{{item.name}}
        </el-menu-item>
      </el-menu>
    </div>
  </div>
</template>

<script>

  export default {
    name: "f2bpm-datagrid",
    watch: {
      data(val, oldVal) {
        var that = this;
        //默认是立即执行
        console.info("f2bpm-datagrid");
        if (val != undefined) {
          var data = val;
          that.checkedAll = false;
          data.forEach(function (item, index) {
            item._selectedkey = Object.toGuid();
            item._checked = false;
          });
          that.rows = data;
        }
      }
    },
    props: {
      //使用full-12的表达式，窗口高度减去指定高度,默认自适应
      height: {},
      //是否加载loading
      loading: { type: Boolean, default: () => { return false; } },
      //是否带有纵向边框
      border: { type: Boolean, default: () => { return true; } },
      //是否为斑马纹 table
      stripe: { type: Boolean, default: () => { return true; } },
      //主键字段名
      pk: { type: String, },
      //列表id
      grid: { type: String, required: true },
      //分页配置及总数量 配置,pagination:false不分页
      pagerConfig: { type: Object },
      //列定义
      columns: { type: Array, required: true },
      //列表行数据
      data: { type: Array, required: true },
      //工具格
      toolbar: { type: Object },
      //表头右键菜单{header: {options: headerMenus},className: 'my-menus'}
      contextMenu: { type: Object, default: () => { return { header: { options: [] }, className: 'my-menus' }; } }
    },
    computed: {},
    mounted() {
      var that = this;
      //添加监听
      document.addEventListener("click", this.listen);
      window.onresize = () => {
        return (() => {
          that.autoResizeHeight();
        })();
      };

    },
    created() {
      var that = this;
      //找出序号列和复选框列
      var checkBoxColumn = that.columns.find(c => c.type == 'checkbox' || c.type == 'radio');
      if (checkBoxColumn && !checkBoxColumn.hidden) {
        that.showCheckbox = true;
        that.checkBoxType =  checkBoxColumn.type;
      }
      var seqColumn = that.columns.find(c => c.type == 'seq');
      if (seqColumn && !seqColumn.hidden) {
        that.showSeq = true;
      }
      that.autoResizeHeight();
      if (that.pagerConfig) {
        that.tablePage = that.pagerConfig;
        that.ispager = true;
      }
    },
    data() {
      return {
        //为了可以让表格重新渲染复选框控件
        tableKey: 'table',
        checkedAll: false,
        //单选间距的行数据
        radioVal: '',
        //序号及复选框
        showSeq: false,
        showCheckbox: false,
        checkBoxType: 'checkbox',

        menuVisible: false,
        tableHeight: 300,
        tablePage: {},
        ispager: false,
        //主键所在操作列
        //primaryCol: {},
        tablePage_demo: {
          pageCount: 0,
          sort: "", //排序字段
          order: "asc", //排序方向
          total: 0,
          currentPage: 1,
          pageSize: 15,
          align: "center",
          pageSizes: [2, 10, 15, 20, 50, 100, 200, 500],
          layout: "total, sizes, prev, pager, next",
        },
        rows: []
        // tableData: [
        //     { workflowTitle: '测试1', sheetId: "BE11" },
        //     { workflowTitle: '测试2', sheetId: "BE22" },
        //     { workflowTitle: '测试3', sheetId: "BE33" },
        //     { workflowTitle: '测试4', sheetId: "BE44" }
        // ],
        // tableColumn: [
        //     {
        //         field: "sheetId",
        //         title: "流程单号",
        //         width: 220,
        //         sort: true,
        //         align: "center",
        //         type: "html",
        //         formatter: function (row, column, value, index) {
        //             return value + ":+格式化后的内容";
        //         },
        //     },
        //     {
        //         field: "workflowTitle",
        //         title: "标题",
        //         width: 480,
        //         align: "left",
        //         type: "html",
        //     },
        // ],
      };
    },
    methods: {
      indexMethod(index) {
        //设置序列号
        return (
          (Number(this.tablePage.currentPage) - 1) * Number(this.tablePage.pageSize) + index + 1
        );
      },
      selectAll(selection) {
        var that = this;
        that.checkedAll=selection.length>0;
        that.rows.forEach(function (item, index) {
          item._checked = that.checkedAll;
        });
        var selection = that.rows;
        var obj = { selection: selection, checked: that.checkedAll }
        this.$emit("checkbox-all", obj);
      }
      , checkAllChange(val) {
        var that = this;
        that.rows.forEach(function (item, index) {
          item._checked = val;
        });
        that.tableKey = Object.toGuid();
        var selection = that.rows;
        var obj = { selection: selection, checked: val }
        this.$emit("checkbox-all", obj);
      }
      , selectionChange(selection, row) {
        var isChecked = false;
        selection.forEach(function (item, index) {
          item._checked = true;
          if (row._selectedkey == item._selectedkey) {
            isChecked = true;
          }
        });
        row._checked = isChecked;
        var obj = { row: row, checked: isChecked }
        this.$emit("checkbox-change", obj);
      }
      //设置选中或取消选中的行
      , toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.f2bpmuiVuetable.toggleRowSelection(row);
          });
        } else {
          this.$refs.f2bpmuiVuetable.clearSelection();
        }
      }
      // , checkedChange(isChecked, row) {
      //   //先放过，后面修正
      //   var that = this;
      //   that.tableKey = Object.toGuid();
      //   row._checked = isChecked;
      //   console.info(isChecked);
      //   console.info(row._checked);
      //   console.info(row);
      //   var obj = { row: row, checked: isChecked }
      //   this.$emit("checkbox-change", obj);
      // }
      , radioChange(row) {
        var that = this;
        var obj = { row: that.radioVal, checked: that.radioVal_checked }
        this.$emit("radio-change", obj);
      }
      //获取选中的行
      , getCheckboxRecords() {
        var that = this;
        var list = [];
        if (that.checkBoxType == 'radio') {
          list.push(that.radioVal);
        } else {
          list = that.rows.filter(d => d._checked);
        }
        console.info(list);
        return list;
      }
      //双击单元格时触发
      , celldblclick(row, column, cell, event) {
        this.$emit("cell-dblclick", { row: row, column: column, cell: cell, event: event });
      },
      //格式化
      filterFormatter: function (row, col, value, index) {
        var fun = col.formatter;
        var result = fun(row, col, value, index);
        return result;
      },
      //执行slots渲染 JSX 渲染函数
      renderToHtml(col, row, index) {
        if (typeof col.slots) {
          this.$slots[col.field] = [
            col.slots.default({ row: row, column: col, index: index, }, this.$createElement),
          ];
          return;
        }
        return;
      },
      //操作列按钮点击
      operateClick() {

      }
      , sortChange({ column, prop, order }) {
        var orderName = order == "ascending" ? "asc" : "desc";
        this.$emit("sort-change", { column: column, field: prop, order: orderName, });
      },
      pageSizeChange(val) {
        var that = this;
        this.$emit("page-change", {
          currentPage: 1,
          pageSize: val,
        });
      },
      pageChange(val) {
        var that = this;
        this.$emit("page-change", {
          currentPage: val,
          pageSize: that.tablePage.pageSize,
        });
      },
      toolbarClick(btn, enent) {
        this.$emit("toolbar-button-click", { code: btn.code, btn: btn }, enent);
      }
      , autoResizeHeight() {
        var that = this;
        var theHeight = $(window).height();
        if (that.height) {
          if (typeof that.height == "string") {
            theHeight = eval(that.height.replace("full", theHeight + ""));
          } else {
            theHeight = that.height;
          }

        } else if (that.toolbar && that.toolbar.buttons.length > 0) {
          //默认情况:有工具栏时
          theHeight = theHeight - 190;
        } else {
          //无工具栏时 
          theHeight = theHeight - 170;
        }
        that.tableHeight = theHeight;
      }
      //表头右键点击时弹出菜单
      , headRightClick(column, event) {
        this.menuVisible = true
        let menu = document.querySelector("#gridHeadMenu");
        menu.style.left = event.clientX - 210 + "px";
        menu.style.top = event.clientY - 50 + "px";
        //取消默认的行为
        event.preventDefault();
        //阻止一个事件起泡。
        event.stopPropagation();
      }
      //表头菜单点击事件
      , headMenuClickEvent(code) {
        this.$emit("header-contextmenu", code);
      }
      , listen() {
        this.menuVisible = false;
      }
    }
  };
</script>